package com.zhitong.money.configs;

import com.zhitong.money.entity.Permission;
import com.zhitong.money.entity.Role;
import com.zhitong.money.entity.TokenEntity;
import com.zhitong.money.entity.User;
import com.zhitong.money.mapper.ITokenEntityMapper;
import com.zhitong.money.mapper.UserMapper;
import com.zhitong.money.services.api.ITokenEntityService;
import lombok.extern.slf4j.Slf4j;

import org.apache.shiro.SecurityUtils;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.mgt.DefaultSecurityManager;

import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ITokenEntityService tokenEntityService;
    //    授权

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        User user = (User) principalCollection.getPrimaryPrincipal();
        List<Role> roles = user.getRoles();

        //添加角色和权限
        Set<String> r= new HashSet<>();
        Set<String> p = new HashSet<>();
        for (Role role : roles) {
            r.add(role.getName());
            List<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                p.add(permission.getName());
            }
        }
        simpleAuthorizationInfo.setRoles(r);
        simpleAuthorizationInfo.setStringPermissions(p);



        return simpleAuthorizationInfo;
    }

//    认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String token = (String) authenticationToken.getPrincipal();
        TokenEntity byToken = tokenEntityService.findByToken(token);

        if (byToken==null || byToken.getExpireTime().getTime()< System.currentTimeMillis()){
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }

        User userByTid = userMapper.findUserByTid(byToken.getTid());

        if (userByTid==null){
            throw new UnknownAccountException("用户不存在!");
        }

        if (userByTid.getStatus().equals("00")){
            throw new LockedAccountException("用户已被冻结!");
        }

        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(userByTid,token,this.getName());


        return info;
    }
}
